{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from PIL import Image\n",
    "import os"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "31\n",
      "10000\n",
      "20000\n",
      "30000\n",
      "40000\n",
      "50000\n",
      "60000\n",
      "70000\n",
      "80000\n",
      "90000\n",
      "100000\n",
      "110000\n",
      "120000\n",
      "130000\n",
      "140000\n",
      "150000\n",
      "160000\n",
      "170000\n",
      "180000\n",
      "190000\n",
      "200000\n",
      "210000\n",
      "220000\n",
      "230000\n",
      "240000\n",
      "250000\n",
      "260000\n",
      "270000\n",
      "280000\n",
      "[ 77.79408427  89.68194542 101.41694189]\n",
      "[320.80931255 297.95251439 289.68621711]\n"
     ]
    }
   ],
   "source": [
    "# 统计train数据集中图像的均值\n",
    "train_data_folder = 'D:/Data/mc_data/train/images/0/'\n",
    "# print(len(train_data_folder))\n",
    "\n",
    "avg_n = np.zeros(3)\n",
    "var_n = np.zeros(3)\n",
    "\n",
    "n = 1\n",
    "for filename in os.listdir(train_data_folder):\n",
    "#     print(train_data_folder+filename)\n",
    "    im = Image.open(train_data_folder+filename)\n",
    "#     print(im.format, im.size, im.mode)\n",
    "    imgarr = np.array(im)\n",
    "#     print(imgarr.shape)\n",
    "    r_arr = np.reshape(imgarr[:,:,0], -1) # R\n",
    "    r_mean = np.mean(r_arr)\n",
    "    g_arr = np.reshape(imgarr[:,:,1], -1) # G\n",
    "    g_mean = np.mean(g_arr)\n",
    "    b_arr = np.reshape(imgarr[:,:,2], -1) # B\n",
    "    b_mean = np.mean(b_arr)\n",
    "    \n",
    "    if n == 1:\n",
    "        avg_n = np.array([r_mean, g_mean, b_mean])\n",
    "    else:\n",
    "        avg_n = avg_n + (np.array([r_mean, g_mean, b_mean]) - avg_n)/n\n",
    "        var_n = var_n*(n-2)/(n-1) + np.square((np.array([r_mean, g_mean, b_mean]) - avg_n))/n\n",
    "    \n",
    "    if n % 10000 == 0:\n",
    "        print(n)\n",
    "    n += 1\n",
    "\n",
    "print(avg_n)\n",
    "print(var_n)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
